#{extends 'main.html' /}
#{set title:'Home' /}
 
<script type="text/javascript">

var sensitiveAreaHeight = 276; 

var start = 12;

//is it loading
var loading = false;

//is it completed
var finished = false;

function onStartLoading() {
	loading = true;
	jQuery("#loadingDivContainer").show();
}

function isLoading() {
	return loading;
}

function onLoaded() {
	loading = false;
	jQuery("#loadingDivContainer").hide();
}

$(document).ready(function() {
	$(window).scroll(function () { 
		if (!finished) {
			var viewPortHeight = $(window).height();
			var documentHeight = $(document).height();
			var scrollTop = $(window).scrollTop();
			if (scrollTop + viewPortHeight > documentHeight - sensitiveAreaHeight) {
				//get more element
				if (!isLoading()) {
					onStartLoading();
					$.getJSON('api/posts?from='+start+'&count=6', function(data) {
						if (data.length == 0) {
							finished = true;
						} else {
							start = start += data.length;
							for (var pos in data) {
								var post = data[pos];
								//get each item to display it
								var postedAt = new Date(post.postedAt);
								var html = ""
								+	'<a href="post/'+post.id+'">'
								+		'<div class="post thumbnail">'
								+			'<div class="post-image">';
								if (post.mainImage) {
									html += 	'<img src="'+post.mainImage.thumbnailUrl +'" alt="'+post.title+'" height="246" width="246" />'
								}
							    html +=		'</div>'
								+			'<div class="post-metadata">'
							    +    			'<div class="post-title">'+post.title+'</div>'
							    +				'<div class="post-date">'+dateFormat(post.postedAt, 'dd mmmm yyyy')+'</div>'
								+			'</div>'
								+		'</div>'
								+	'</a>';
		
								$(html).insertBefore("#clearer");
							}
						}

						onLoaded();
					});
				}
			}
		}
	});

});
</script>

 
#{if posts.size()}
    ${user}
    #{list items:posts, as:'post'}
    	#{displayPost post:post, as:'thumbnail', user:user /}
    #{/list}
    
    <div style="clear:both" id="clearer"></div>
    
	<!-- Loading div -->
	<div id="loadingDivContainer" style="display:none">
		<center>
			<div id="loadingDiv">Loading</div>
		</center>
	</div>
    
#{/if}
 
#{else}
    <div class="empty">
        There is currently nothing to read here.
    </div>
#{/else}